import dayjs from '../../dayjs.min'
import { login } from "../../services/user";
import { saveToken } from '../../utils/util'

const app = getApp()

Page({
  data: {
    pwdFocused: false,
    usernameEmpty: true,
    pwdEmpty: true,
    logining: false
  },

  focusPwd: function (e) {
    this.setData({
      'pwdFocused': true
    })
  },
  changeUsername: function ({ detail: { value } }) {
    this.setData({
      'usernameEmpty': !Boolean(value.trim())
    })
  },
  changePassword: function ({ detail: { value } }) {
    this.setData({
      'pwdEmpty': !Boolean(value)
    })
  },
  formSubmit: function ({ detail: { value } }) {
    if (this.data.logining) {
      return
    }

    this.setData({ logining: true })

    login(value).then((data) => {
      const { token, ...userInfo } = data
      app.state.userInfo = userInfo

      const { access_token, expires_in } = token
      const expire_date = dayjs().add(expires_in, 'day')
      saveToken(access_token, expire_date.toJSON())
      this.setData({ logining: false })

      wx.reLaunch({
        url: '../index/index'
      })
    }).catch(({ code }) => {
      if (code && code === 4003) {
        wx.showToast({
          title: '用户名不存在，或密码错误',
          icon: 'none'
        })
      }
      this.setData({ logining: false })
    })
  }
})